<!DOCTYPE html>




<html class="theme-next gemini" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />



  <meta name="google-site-verification" content="vjImUBDCK8Rg9G13vkIip_GUsZTtVV6s-XdSk81-jzA" />













  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.lug.ustc.edu.cn/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.2" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Kotlin,RecyclerView," />





  <link rel="alternate" href="/atom.xml" title="旺仔的个人博客" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.png?v=5.1.2" />






<meta name="description" content="前言RecyclerView出来很久了，可以说一出来就将ListView给比下去了，当然，Recyclerview有它的好，ListView的好，并不是说一定要用Recyclerview，最适用自己项目的才是最好的。 在这里我们将用Kotlin来实现RecyclerView的多种item布局，和单个item布局，同时写一个通用的Adapter。">
<meta name="keywords" content="Kotlin,RecyclerView">
<meta property="og:type" content="article">
<meta property="og:title" content="Kotlin实战_实现RecyclerView多种Item布局">
<meta property="og:url" content="http://www.jowanxu.top/2017/06/09/Kotlin实战_实现RecyclerView多种Item布局/index.html">
<meta property="og:site_name" content="旺仔的个人博客">
<meta property="og:description" content="前言RecyclerView出来很久了，可以说一出来就将ListView给比下去了，当然，Recyclerview有它的好，ListView的好，并不是说一定要用Recyclerview，最适用自己项目的才是最好的。 在这里我们将用Kotlin来实现RecyclerView的多种item布局，和单个item布局，同时写一个通用的Adapter。">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/1241355-4c6e971a09036c8e.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/1241355-704a68a70b901398.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/1241355-31718e1eaa57e6e5.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:updated_time" content="2017-11-29T00:19:59.479Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Kotlin实战_实现RecyclerView多种Item布局">
<meta name="twitter:description" content="前言RecyclerView出来很久了，可以说一出来就将ListView给比下去了，当然，Recyclerview有它的好，ListView的好，并不是说一定要用Recyclerview，最适用自己项目的才是最好的。 在这里我们将用Kotlin来实现RecyclerView的多种item布局，和单个item布局，同时写一个通用的Adapter。">
<meta name="twitter:image" content="http://upload-images.jianshu.io/upload_images/1241355-4c6e971a09036c8e.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: false,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://www.jowanxu.top/2017/06/09/Kotlin实战_实现RecyclerView多种Item布局/"/>





  <title>Kotlin实战_实现RecyclerView多种Item布局 | 旺仔的个人博客</title>
  














</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>
    <a href="https://github.com/wangzailfm"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://camo.githubusercontent.com/38ef81f8aca64bb9a64448d0d70f1308ef5341ab/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f6461726b626c75655f3132313632312e706e67" alt="Fork me on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png"></a>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">旺仔的个人博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">叫我旺仔<br/>Android Developer</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-commonweal">
          <a href="/404.html" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br />
            
            公益
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://www.jowanxu.top/2017/06/09/Kotlin实战_实现RecyclerView多种Item布局/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Jowan">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="旺仔的个人博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Kotlin实战_实现RecyclerView多种Item布局</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-06-09T09:01:59+08:00">
                2017-06-09
              </time>
            

            
              <span class="post-meta-divider">|</span>
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-check-o"></i>
              </span>
              
                <span class="post-meta-item-text">更新于</span>
              
              <time title="更新于" itemprop="dateModified" datetime="2017-11-29T08:19:59+08:00">
                2017-11-29
              </time>
            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Kotlin/" itemprop="url" rel="index">
                    <span itemprop="name">Kotlin</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"> 文章热度</i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>°C
            </span>
          

          
            <br/>
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">文章字数</span>
                
                <span title="文章字数">
                  1,247 字
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长需</span>
                
                <span title="阅读时长需">
                  6 分钟
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2><p>RecyclerView出来很久了，可以说一出来就将ListView给比下去了，当然，Recyclerview有它的好，ListView的好，并不是说一定要用Recyclerview，最适用自己项目的才是最好的。</p>
<p>在这里我们将用Kotlin来实现RecyclerView的多种item布局，和单个item布局，同时写一个通用的Adapter。</p>
<a id="more"></a>
<h2 id="使用"><a href="#使用" class="headerlink" title="使用"></a>使用</h2><p>先将写完的代码的使用方式展示一下：</p>
<h3 id="一种item布局"><a href="#一种item布局" class="headerlink" title="一种item布局"></a>一种item布局</h3><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line"><span class="class"><span class="keyword">class</span> <span class="title">SingleItemAdapter</span></span>(mContext: Context, mDatas: List&lt;TestBean&gt;)</div><div class="line">    : DelegateItemAdapter&lt;TestBean&gt;(mContext, mDatas) &#123;</div><div class="line">    init &#123;</div><div class="line">        addItemViewDelegate(SingleItemDelegate())</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>效果图</p>
<p><img src="http://upload-images.jianshu.io/upload_images/1241355-4c6e971a09036c8e.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="SingleItem"></p>
<h3 id="多种item布局"><a href="#多种item布局" class="headerlink" title="多种item布局"></a>多种item布局</h3><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line"><span class="class"><span class="keyword">class</span> <span class="title">MultiItemAdapter</span></span>(mContext: Context, mDatas: List&lt;TestBean&gt;) </div><div class="line">    : DelegateItemAdapter&lt;TestBean&gt;(mContext, mDatas) &#123;</div><div class="line">    init &#123;</div><div class="line">        addItemViewDelegate(LeftDelegate())</div><div class="line">        addItemViewDelegate(CenterDelegate())</div><div class="line">        addItemViewDelegate(RightDelegate())</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>效果图</p>
<p><img src="http://upload-images.jianshu.io/upload_images/1241355-704a68a70b901398.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="MultiItem"></p>
<h2 id="梳理"><a href="#梳理" class="headerlink" title="梳理"></a>梳理</h2><p>总体流程是这样的，首先创建itemView，在里面设置layoutId和数据处理，然后创建一个类继承<code>DelegateItemAdapter</code>，并在主构造方法里面添加不同的itemView，然后Adapter通过<code>DelegateManager</code>类来管理对应的itemView进行操作。</p>
<h3 id="ItemView"><a href="#ItemView" class="headerlink" title="ItemView"></a>ItemView</h3><p>我们的itemView是实现<code>DelegateType</code>接口，然后在里面设置相对应的layoutId，对数据进行操作处理：<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div></pre></td><td class="code"><pre><div class="line"><span class="class"><span class="keyword">class</span> <span class="title">SingleItemDelegate</span> : <span class="type">DelegateType</span>&lt;<span class="type">TestBean</span>&gt; </span>&#123;</div><div class="line">    <span class="keyword">override</span> <span class="keyword">val</span> itemViewLayoutId: <span class="built_in">Int</span></div><div class="line">        <span class="keyword">get</span>() = R.layout.item_left</div><div class="line"></div><div class="line">    <span class="keyword">override</span> <span class="function"><span class="keyword">fun</span> <span class="title">isItemViewType</span><span class="params">(item: <span class="type">TestBean</span>, position: <span class="type">Int</span>)</span></span>: <span class="built_in">Boolean</span> = <span class="literal">true</span></div><div class="line"></div><div class="line">    <span class="keyword">override</span> <span class="function"><span class="keyword">fun</span> <span class="title">convert</span><span class="params">(context: <span class="type">Context</span>, holder: <span class="type">ViewHolder</span>, item: <span class="type">TestBean</span>, position: <span class="type">Int</span>)</span></span> &#123;</div><div class="line">        with(holder.itemView) &#123;</div><div class="line">            item_left_text.text = item.text</div><div class="line">            setOnClickListener &#123;</div><div class="line">                context.toast(<span class="string">"SingleItemDelegate"</span>)</div><div class="line">            &#125;</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<h3 id="ViewHolder"><a href="#ViewHolder" class="headerlink" title="ViewHolder"></a>ViewHolder</h3><p>在使用Recyclerview的时候，必须有ViewHolder，通常情况下，我们需要写一个通用的ViewHolder，但是在Kotlin中的话，就不需要那样写，因为Kotlin可以直接将布局的id来当成变量使用，所以我们需要写一个ViewHolder类来继承Recyclerview里面的Viewholder类。</p>
<p>使用id当变量的话，要在<code>app</code>下面的<code>build.gradle</code>里面加个<code>plugin: &#39;kotlin-android-extensions&#39;</code></p>
<p><img src="http://upload-images.jianshu.io/upload_images/1241355-31718e1eaa57e6e5.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="extensions"></p>
<figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div></pre></td><td class="code"><pre><div class="line"><span class="class"><span class="keyword">class</span> <span class="title">ViewHolder</span></span>(itemView: View) : RecyclerView.ViewHolder(itemView) &#123;</div><div class="line"></div><div class="line">    <span class="keyword">companion</span> <span class="keyword">object</span> &#123;</div><div class="line">        <span class="comment">/**</span></div><div class="line"><span class="comment">         * 创建ViewHolder</span></div><div class="line"><span class="comment">         *</span></div><div class="line"><span class="comment">         * <span class="doctag">@param</span> itemView itemView</span></div><div class="line"><span class="comment">         * <span class="doctag">@return</span> ViewHolder</span></div><div class="line"><span class="comment">         */</span></div><div class="line">        <span class="function"><span class="keyword">fun</span> <span class="title">createViewHolder</span><span class="params">(itemView: <span class="type">View</span>)</span></span>: ViewHolder &#123;</div><div class="line">            <span class="keyword">val</span> holder = ViewHolder(itemView)</div><div class="line">            <span class="keyword">return</span> holder</div><div class="line">        &#125;</div><div class="line"></div><div class="line">        <span class="comment">/**</span></div><div class="line"><span class="comment">         * 创建ViewHolder</span></div><div class="line"><span class="comment">         *</span></div><div class="line"><span class="comment">         * <span class="doctag">@param</span> context Context</span></div><div class="line"><span class="comment">         * <span class="doctag">@param</span> parent ViewGroup</span></div><div class="line"><span class="comment">         * <span class="doctag">@param</span> layoutId layoutId</span></div><div class="line"><span class="comment">         * <span class="doctag">@return</span> ViewHolder</span></div><div class="line"><span class="comment">         */</span></div><div class="line">        <span class="function"><span class="keyword">fun</span> <span class="title">createViewHolder</span><span class="params">(context: <span class="type">Context</span>,</span></span></div><div class="line"><span class="function"><span class="params">                             parent: <span class="type">ViewGroup</span>, layoutId: <span class="type">Int</span>)</span></span>: ViewHolder &#123;</div><div class="line">            <span class="keyword">val</span> itemView = LayoutInflater.from(context).inflate(layoutId, parent,</div><div class="line">                    <span class="literal">false</span>)</div><div class="line">            <span class="keyword">val</span> holder = ViewHolder(itemView)</div><div class="line">            <span class="keyword">return</span> holder</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>这样子ViewHolder就搞定了，不需要在写那些设置text、image、绑定事件相关的代码了。</p>
<h3 id="Adapter"><a href="#Adapter" class="headerlink" title="Adapter"></a>Adapter</h3><p>那么我们改如何区分多种itemView呢，在这里我们引用了一个接口：<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div></pre></td><td class="code"><pre><div class="line"><span class="comment">/**</span></div><div class="line"><span class="comment"> * itemView属性</span></div><div class="line"><span class="comment"> */</span></div><div class="line"><span class="class"><span class="keyword">interface</span> <span class="title">DelegateType</span>&lt;<span class="type">in T</span>&gt; </span>&#123; <span class="comment">// 由于T只是作为参数，所以T是contravariant逆变，加in</span></div><div class="line">    <span class="comment">/**</span></div><div class="line"><span class="comment">     * 获取layoutId</span></div><div class="line"><span class="comment">     */</span></div><div class="line">    <span class="keyword">val</span> itemViewLayoutId: <span class="built_in">Int</span></div><div class="line"></div><div class="line">    <span class="comment">/**</span></div><div class="line"><span class="comment">     * 判断类型</span></div><div class="line"><span class="comment">     *</span></div><div class="line"><span class="comment">     * <span class="doctag">@param</span> item data数据</span></div><div class="line"><span class="comment">     * <span class="doctag">@param</span> position 当前position</span></div><div class="line"><span class="comment">     * <span class="doctag">@return</span> true显示数据</span></div><div class="line"><span class="comment">     */</span></div><div class="line">    <span class="function"><span class="keyword">fun</span> <span class="title">isItemViewType</span><span class="params">(item: <span class="type">T</span>, position: <span class="type">Int</span>)</span></span>: <span class="built_in">Boolean</span></div><div class="line"></div><div class="line">    <span class="comment">/**</span></div><div class="line"><span class="comment">     * 显示数据</span></div><div class="line"><span class="comment">     *</span></div><div class="line"><span class="comment">     * <span class="doctag">@param</span> context Context</span></div><div class="line"><span class="comment">     * <span class="doctag">@param</span> holder ViewHolder</span></div><div class="line"><span class="comment">     * <span class="doctag">@param</span> item data数据</span></div><div class="line"><span class="comment">     * <span class="doctag">@param</span> position 当前position</span></div><div class="line"><span class="comment">     */</span></div><div class="line">    <span class="function"><span class="keyword">fun</span> <span class="title">convert</span><span class="params">(context: <span class="type">Context</span>, holder: <span class="type">ViewHolder</span>, item: <span class="type">T</span>, position: <span class="type">Int</span>)</span></span></div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>根据layoutId来创建对应的ViewHolder，并且通过<code>isItemViewType</code>方法来匹配是否是当前itemView类型，然后通过convert来显示数据。</p>
<p>Adapter是继承Recyclerview里面的Adapter，传入ViewHolder，传入泛型数据集，那么我们可以通过传入的数据集里面的类型来判断不同的itemView，在这里需要重写几个方法：</p>
<p><strong>getItemViewType方法</strong><br>根据数据来返回不同类型：<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line"><span class="comment">/**</span></div><div class="line"><span class="comment"> * 获取itemView类型</span></div><div class="line"><span class="comment"> *</span></div><div class="line"><span class="comment"> * <span class="doctag">@param</span> position 当前position</span></div><div class="line"><span class="comment"> */</span></div><div class="line"><span class="keyword">override</span> <span class="function"><span class="keyword">fun</span> <span class="title">getItemViewType</span><span class="params">(position: <span class="type">Int</span>)</span></span>: <span class="built_in">Int</span> = <span class="keyword">if</span> (!useItemViewDelegateManager())</div><div class="line">    <span class="keyword">super</span>.getItemViewType(position)</div><div class="line"><span class="keyword">else</span></div><div class="line">    mDelegateManager.getItemViewType(mDatas[position], position)</div></pre></td></tr></table></figure></p>
<p><strong>onCreateViewHolder方法</strong><br>根据<code>mDelegateManager.getItemViewDelegate(viewType).itemViewLayoutId</code>返回的layoutId来生成对应的ViewHolder<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">override</span> <span class="function"><span class="keyword">fun</span> <span class="title">onCreateViewHolder</span><span class="params">(parent: <span class="type">ViewGroup</span>, viewType: <span class="type">Int</span>)</span></span>: ViewHolder = ViewHolder.createViewHolder(mContext, parent, mDelegateManager.getItemViewDelegate(viewType).itemViewLayoutId)</div></pre></td></tr></table></figure></p>
<p><strong>onBindViewHolder方法</strong><br>用于数据处理和显示：<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">override</span> <span class="function"><span class="keyword">fun</span> <span class="title">onBindViewHolder</span><span class="params">(holder: <span class="type">ViewHolder</span>, position: <span class="type">Int</span>)</span></span> = convert(holder, mDatas[position])</div></pre></td></tr></table></figure></p>
<p>上面的<code>mDelegateManager</code>是管理itemView的类，可以添加删除itemView，并且显示数据：<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div><div class="line">68</div><div class="line">69</div><div class="line">70</div><div class="line">71</div><div class="line">72</div><div class="line">73</div><div class="line">74</div><div class="line">75</div><div class="line">76</div><div class="line">77</div><div class="line">78</div><div class="line">79</div><div class="line">80</div><div class="line">81</div><div class="line">82</div><div class="line">83</div><div class="line">84</div><div class="line">85</div><div class="line">86</div><div class="line">87</div><div class="line">88</div><div class="line">89</div><div class="line">90</div><div class="line">91</div></pre></td><td class="code"><pre><div class="line"><span class="comment">/**</span></div><div class="line"><span class="comment">* 获取itemView的类型</span></div><div class="line"><span class="comment">*</span></div><div class="line"><span class="comment">* <span class="doctag">@param</span> item data数据</span></div><div class="line"><span class="comment">* <span class="doctag">@param</span> position 当前position</span></div><div class="line"><span class="comment">* <span class="doctag">@return</span> Int</span></div><div class="line"><span class="comment">*/</span></div><div class="line"><span class="function"><span class="keyword">fun</span> <span class="title">getItemViewType</span><span class="params">(item: <span class="type">T</span>, position: <span class="type">Int</span>)</span></span>: <span class="built_in">Int</span> &#123;</div><div class="line">    (<span class="number">0.</span>. delegateCount - <span class="number">1</span>)</div><div class="line">            .filter &#123; mDelegates.valueAt(it).isItemViewType(item, position) &#125;</div><div class="line">            .forEach &#123; <span class="keyword">return</span> mDelegates.keyAt(it) &#125;</div><div class="line">    <span class="keyword">throw</span> IllegalArgumentException(</div><div class="line">            <span class="string">"No ItemViewDelegate added that matches position = <span class="variable">$position</span> in data = <span class="variable">$item</span> source"</span>);</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="comment">/**</span></div><div class="line"><span class="comment">* 显示数据</span></div><div class="line"><span class="comment">*</span></div><div class="line"><span class="comment">* <span class="doctag">@param</span> context Context</span></div><div class="line"><span class="comment">* <span class="doctag">@param</span> holder ViewHolder</span></div><div class="line"><span class="comment">* <span class="doctag">@param</span> item data数据</span></div><div class="line"><span class="comment">* <span class="doctag">@param</span> position 当前position</span></div><div class="line"><span class="comment">*/</span></div><div class="line"><span class="function"><span class="keyword">fun</span> <span class="title">convert</span><span class="params">(context: <span class="type">Context</span>, holder: <span class="type">ViewHolder</span>, item: <span class="type">T</span>, position: <span class="type">Int</span>)</span></span> &#123;</div><div class="line">    <span class="keyword">for</span> (i <span class="keyword">in</span> <span class="number">0.</span>.delegateCount - <span class="number">1</span>) &#123;</div><div class="line">        <span class="keyword">val</span> delegate = mDelegates.valueAt(i)</div><div class="line">        <span class="keyword">if</span> (delegate.isItemViewType(item, position)) &#123;</div><div class="line">            delegate.convert(context, holder, item, position);</div><div class="line">            <span class="keyword">return</span><span class="symbol">@convert</span></div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">    <span class="keyword">throw</span> IllegalArgumentException(</div><div class="line">            <span class="string">"No ItemViewDelegateManager added that matches position= <span class="variable">$position</span> in data = <span class="variable">$item</span> source"</span>)</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="comment">/**</span></div><div class="line"><span class="comment">* 添加itemView</span></div><div class="line"><span class="comment">*</span></div><div class="line"><span class="comment">* <span class="doctag">@param</span> delegate itemView</span></div><div class="line"><span class="comment">* <span class="doctag">@throws</span> IllegalArgumentException 已存在不能再添加</span></div><div class="line"><span class="comment">* <span class="doctag">@return</span> DelegateManager</span></div><div class="line"><span class="comment">*/</span></div><div class="line"><span class="function"><span class="keyword">fun</span> <span class="title">addDelegate</span><span class="params">(delegate: <span class="type">DelegateType</span>&lt;<span class="type">T</span>&gt;)</span></span>: DelegateManager&lt;T&gt; &#123;</div><div class="line">    <span class="keyword">for</span> (i <span class="keyword">in</span> <span class="number">0.</span>.delegateCount - <span class="number">1</span>) &#123;</div><div class="line">        <span class="keyword">if</span> (mDelegates.valueAt(i).itemViewLayoutId == delegate.itemViewLayoutId) &#123;</div><div class="line">            <span class="keyword">throw</span> IllegalArgumentException(<span class="string">"An ItemViewDelegate is already registered for the delegate = <span class="variable">$delegate</span>."</span>)</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">    mDelegates.put(mDelegates.size(), delegate)</div><div class="line">    <span class="keyword">return</span> <span class="keyword">this</span></div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="comment">/**</span></div><div class="line"><span class="comment">* 添加itemView</span></div><div class="line"><span class="comment">*</span></div><div class="line"><span class="comment">* <span class="doctag">@param</span> viewType 代表itemView的下标</span></div><div class="line"><span class="comment">* <span class="doctag">@param</span> delegate itemView</span></div><div class="line"><span class="comment">* <span class="doctag">@throws</span> IllegalArgumentException 已存在不能再添加</span></div><div class="line"><span class="comment">* <span class="doctag">@return</span> DelegateManager</span></div><div class="line"><span class="comment">*/</span></div><div class="line"><span class="function"><span class="keyword">fun</span> <span class="title">addDelegate</span><span class="params">(viewType: <span class="type">Int</span>, delegate: <span class="type">DelegateType</span>&lt;<span class="type">T</span>&gt;)</span></span>: DelegateManager&lt;T&gt; &#123;</div><div class="line">    <span class="keyword">if</span> (mDelegates.<span class="keyword">get</span>(viewType) != <span class="literal">null</span>) &#123;</div><div class="line">        <span class="keyword">throw</span> IllegalArgumentException(<span class="string">"An ItemViewDelegate is already registered for the viewType = <span class="variable">$viewType</span>. Already registered ItemViewDelegate is <span class="subst">$&#123;mDelegates.get(viewType)&#125;</span>"</span>)</div><div class="line">    &#125;</div><div class="line">    mDelegates.put(viewType, delegate)</div><div class="line">    <span class="keyword">return</span> <span class="keyword">this</span></div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="comment">/**</span></div><div class="line"><span class="comment"> * 获取itemView</span></div><div class="line"><span class="comment"> *  </span></div><div class="line"><span class="comment"> * <span class="doctag">@param</span> viewType 代表itemView的下标</span></div><div class="line"><span class="comment"> * <span class="doctag">@return</span> DelegateType</span></div><div class="line"><span class="comment"> */</span></div><div class="line"><span class="function"><span class="keyword">fun</span> <span class="title">getItemViewDelegate</span><span class="params">(viewType: <span class="type">Int</span>)</span></span>: DelegateType&lt;T&gt; = mDelegates.<span class="keyword">get</span>(viewType)</div><div class="line"></div><div class="line"><span class="comment">/**</span></div><div class="line"><span class="comment"> * 获取itemView的LayoutId</span></div><div class="line"><span class="comment"> *</span></div><div class="line"><span class="comment"> * <span class="doctag">@param</span> viewType 代表itemView的下标</span></div><div class="line"><span class="comment"> * <span class="doctag">@return</span> Int</span></div><div class="line"><span class="comment">*/</span></div><div class="line"><span class="function"><span class="keyword">fun</span> <span class="title">getItemViewLayoutId</span><span class="params">(viewType: <span class="type">Int</span>)</span></span>: <span class="built_in">Int</span> = getItemViewDelegate(viewType).itemViewLayoutId</div><div class="line"></div><div class="line"><span class="comment">/**</span></div><div class="line"><span class="comment">* 获取itemView的类型</span></div><div class="line"><span class="comment">*</span></div><div class="line"><span class="comment">* <span class="doctag">@param</span> delegate itemView</span></div><div class="line"><span class="comment">* <span class="doctag">@return</span> Int</span></div><div class="line"><span class="comment">*/</span></div><div class="line"><span class="function"><span class="keyword">fun</span> <span class="title">getItemViewType</span><span class="params">(delegate: <span class="type">DelegateType</span>&lt;<span class="type">T</span>&gt;)</span></span>: <span class="built_in">Int</span> = mDelegates.indexOfValue(delegate)</div></pre></td></tr></table></figure></p>
<p>通过使用<code>addDelegate</code>方法添加itemView，然后通过<code>getItemViewType</code>方法来获取itemView的类型，最后通过<code>convert</code>方法来进行数据操作和显示，这样子我们的Adapter就写出来了。</p>
<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><p>每次写Recyclerview的时候都要重复写这些Adapter，ViewHolder的代码，这里将它写成通用的，可以省去很多的时间。</p>
<p>注意：项目是在3.0版本的Android Studio上运行。</p>
<p>源码：<a href="https://github.com/wangzailfm/RvAdapterForKotlin" target="_blank" rel="external">Github</a>，欢迎star。</p>
<p>参考：<a href="http://blog.csdn.net/lmj623565791/article/details/51118836" target="_blank" rel="external">为RecyclerView打造通用Adapter 让RecyclerView更加好用</a></p>

      
    </div>
    
    
    

    

    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    Jowan
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://www.jowanxu.top/2017/06/09/Kotlin实战_实现RecyclerView多种Item布局/" title="Kotlin实战_实现RecyclerView多种Item布局">http://www.jowanxu.top/2017/06/09/Kotlin实战_实现RecyclerView多种Item布局/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Kotlin/" rel="tag"><i class="fa fa-tag"></i> Kotlin</a>
          
            <a href="/tags/RecyclerView/" rel="tag"><i class="fa fa-tag"></i> RecyclerView</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/05/31/Kotlin学习_泛型/" rel="next" title="Kotlin学习_泛型（Generics）">
                <i class="fa fa-chevron-left"></i> Kotlin学习_泛型（Generics）
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/06/13/Kotlin学习_函数、高级函数和Lambda表达式/" rel="prev" title="Kotlin学习_函数、高级函数和Lambda表达式">
                Kotlin学习_函数、高级函数和Lambda表达式 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zMjA1My84NjE3"></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avatar.gif"
               alt="Jowan" />
          <p class="site-author-name" itemprop="name">Jowan</p>
           
              <p class="site-description motion-element" itemprop="description">叫我旺仔<br/>Android Developer</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives/">
                <span class="site-state-item-count">31</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">5</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">27</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://plus.google.com/u/0/111824269044709365866" target="_blank" title="Google">
                  
                    
                      Google
                    
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://github.com/wangzailfm" target="_blank" title="GitHub">
                  
                    
                      GitHub
                    
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://weibo.com/809077554" target="_blank" title="微博">
                  
                    
                      微博
                    
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="673173629@qq.com" target="_blank" title="E-Mail">
                  
                    
                      E-Mail
                    
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://blog.csdn.net/u011976726" target="_blank" title="CSDN">
                  
                    
                      CSDN
                    
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://www.jianshu.com/u/5509a21c1623" target="_blank" title="简书">
                  
                    
                      简书
                    
                </a>
              </span>
            
          
        </div>

        
        

        
        
          <div class="links-of-blogroll motion-element links-of-blogroll-block">
            <div class="links-of-blogroll-title">
              <i class="fa  fa-fw fa-globe"></i>
              Links
            </div>
            <ul class="links-of-blogroll-list">
              
                <li class="links-of-blogroll-item">
                  <a href="http://wanandroid.com/" title="WanAndroid" target="_blank">WanAndroid</a>
                </li>
              
            </ul>
          </div>
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#使用"><span class="nav-number">2.</span> <span class="nav-text">使用</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#一种item布局"><span class="nav-number">2.1.</span> <span class="nav-text">一种item布局</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#多种item布局"><span class="nav-number">2.2.</span> <span class="nav-text">多种item布局</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#梳理"><span class="nav-number">3.</span> <span class="nav-text">梳理</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#ItemView"><span class="nav-number">3.1.</span> <span class="nav-text">ItemView</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#ViewHolder"><span class="nav-number">3.2.</span> <span class="nav-text">ViewHolder</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Adapter"><span class="nav-number">3.3.</span> <span class="nav-text">Adapter</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#总结"><span class="nav-number">4.</span> <span class="nav-text">总结</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Jowan</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Gemini
  </a>
</div>


        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user">本站访客数</i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人次
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye">本站总访问量</i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>


        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.2"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.2"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.2"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.2"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.2"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  






  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  

  

  

</body>
</html>
